const express = require("express");
const app = express();
const http = require("http").createServer(app);
import chalk from 'chalk';
const io = require("socket.io")(http);
io.set("origins", "*:*");

export default class Socket {
    constructor({ port } = {}) {
        if (!port) return;
        this.port = port || 3000;
        this.list = {};
        this.init();
    }
    init() {
        try {
            io.on("connection", socket => {  // 客户端链接成功
                const query = socket.handshake.query || {};
                this.list[query.uid] = socket;
                // 监听的频道必须和客户端监听的频道相同，等待消息
                socket.on('message', msg => {
                    // 测试代码 正式环境中需要根据自己需求内部编写
                    try {
                        this.list[msg.uid] && this.list[msg.uid].emit("message", `${new Date()} 发送给客户端消息=> ${JSON.stringify(msg.msg)}`);// 向所有客户端发送信息
                    } catch (error) {
                        console.error(error);
                    }
                });
                socket.on("disconnect", socket => {  // 客户端断开链接
                    delete this.list[query.uid];
                });
            });
            http.listen(this.port, _ => {
                console.log(
                    chalk.green(`Socket server running on ${this.port}`)
                )
            });
        } catch (error) {
            console.error(error);
        }
    }
}